package com.zs.grain.ui

import android.app.Application
import android.graphics.BitmapFactory
import android.graphics.drawable.BitmapDrawable
import android.media.MediaPlayer
import android.net.Uri
import android.util.Log
import com.jeremyliao.liveeventbus.LiveEventBus
import com.xnkj1688.semplibrary.entity.Advertisement
import com.xnkj1688.semplibrary.mvvm.BaseViewModel
import com.zs.grain.service.DataService
import io.reactivex.disposables.Disposable
import io.reactivex.schedulers.Schedulers
import io.reactivex.subjects.SingleSubject
import java.io.File
import java.lang.Exception
import javax.inject.Inject

class AdsViewModel @Inject constructor(
    val mApp: Application,
    val mDataService: DataService ) : BaseViewModel(mApp) {

    private var mDisposable: Disposable? = null

    fun init(){
        LiveEventBus.get("RefreshVideoView").post(true)
        mDisposable?.dispose()
        mDisposable = SingleSubject.create<Unit>() {
            try {
                Thread.sleep(1000)
                var advertisements = mDataService.advertisements
                playAdvertisements(mDisposable!!, advertisements)
            } catch (e: Exception) {
                Log.e(MainViewModel.TAG, "广告播放终止：" + e.message)
            }
        }.subscribeOn(Schedulers.io())
            .subscribe({ }, { it.printStackTrace() })
    }

    var advertisement: Advertisement? = null
    fun playAdvertisements(disposable: Disposable, advertisements: List<Advertisement>) {
        var notify = getNotify("Advertisement")
        try {
            var adsPath = mDataService.adsPath
            while (disposable == mDisposable && !disposable.isDisposed) {
                for (item in advertisements) {
                    val file = File(adsPath + item.fileName)
                    if (!file.exists() || !(item.enable ?: false)) continue
                    if (disposable.isDisposed) break

                    notify.putString("FileName", file.absolutePath)//file.absolutePath真实可播的文件
                    uiNotify.postValue(notify)
                    if (item.duration == null) {
                        advertisement = item
                        while (advertisement != null) Thread.sleep(500)
                    } else {
                        Thread.sleep(item.duration * 1000L)
                    }
                }
                Thread.sleep(1000)
            }
        } catch (e: Exception) {
//            e.printStackTrace()
        }
    }

    fun onVideoError(mp: MediaPlayer, what: Int, extra: Int): Boolean {
        mp.stop()
        if (what == MediaPlayer.MEDIA_ERROR_UNKNOWN) {
            advertisement?.enable = false
        }
        advertisement = null
        return false
    }

    fun onVideoCompletion() {
        advertisement = null
    }
}